import { RequestMethod } from "../lib/defines";
import {MemberBase, RoomBase} from "../utils/types";
import {ChatModeEnums} from "../utils/enums";

const { record, stopRecord } = RequestMethod;

type dataType = {
  url: string;
  member: MemberBase;
  room: RoomBase;
}
export default function recording (app) {
  const { socket, rooms, clientUtils } = app.locals;
  const { userId, username } = socket.handshake.query;

  /**
   * 录制视频
   */
  socket.on(record, async function __recording ({ room, member, url }: dataType, cb) {
    const __room = rooms[room.classId]
    if (!__room) return cb && cb({status: 'error', message: 'room not find!'})

    const __member = __room.members[member.userId];
    if (!__member) return cb && cb({status: 'error', message: 'member not find!'})

    const pipeline = __room.members[userId].pipeline;
    if (!pipeline) cb && cb({status: 'error', message: 'pipeline not find!'})

    const endpoint = __member.getEndpoint(userId)
    if (!endpoint) cb && cb({status: 'error', message: `user(userId:${userId}; username:${username}) is not speaker!`})

    /**
     * 录制 播放的视频
     */
    if (__room.chatMode === ChatModeEnums.BROADCAST) {
      return  cb && cb({status: 'error', message: `广播不允许录制!`})
    }

    const __rul = url || `file:///tmp/kurento_record/${Date.now()}`
    // 创建一个录制节点
    const recorder = await clientUtils.createRecordEndpoint(pipeline, __rul);
    // 将【流节点】连接道【录制节点】
    await clientUtils.connect(endpoint, recorder);

    // 缓存 【录制节点】
    __member.recorder = recorder;

    // 流结束时，释放录制，释放播放
    __member.player.on('EndOfStream', async (data) => {
      console.log('EndOfStream', data)
      console.log('停止录制')
      await recorder.stop();

      console.log('释放录制')
      await recorder.release();

      console.log('释放播放器')
      await __member.player.release();
    })

    // 开始录制
    recorder.record(function (error) {
      if (error) return cb({status: 'error', message: error});

      // 返回录制地址
      cb && cb({status: 'ok', data: url})
    })
  });

  /**
   * 停止录制
   */
  socket.on(stopRecord, async function __recordStop ({ room, member, url }: dataType, cb) {
    const __room = rooms[room.classId]
    if (!__room) return cb && cb({status: 'error', message: 'room not find!'})

    const __member = __room.members[member.userId];
    if (!__member) return cb && cb({status: 'error', message: 'member not find!'})

    /**
     * 录制
     */
    if (__room.chatMode === ChatModeEnums.BROADCAST) {}

    __member.player.getUri(function (error, url) {
      if (error) return cb({status: 'error', message: error});

      return __member.recorder.release(function (error) {
        if (error) return cb({status: 'error', message: error});

        return __member.player.release(function (error) {
          if (error) return cb({status: 'error', message: error});

          return cb && cb({status: 'ok', message: url});
        });
      });
    });
  });
}
